/*
 * @(#)JsonMarshaller.java   2015.五月.14 03:54 下午
 * 
 * Copyright (c) 2015 www.7jia2.com
 *
 * 版权声明： 版权所有 违者必究 2015
 *
 */

package com.oaf.response;

//~--- non-JDK imports --------------------------------------------------------

import com.oaf.exception.OafException;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;

//~--- JDK imports ------------------------------------------------------------

import java.io.IOException;
import java.io.OutputStream;

/**
 * @ClassName: JsonMarshaller   
 * @Description:Json的流化
 * @Date:2015.五月.14 03:54 下午
 * @version        0.8, 2015.五月.14 03:54 下午
 * @author         xu.wengang@7jia2.com  
 */
public class JsonMarshaller implements OafMarshaller {
    /** (用一句话描述做什么的.....) */
    private static ObjectMapper objectMapper;

    /**
     * @Title:marshaller
     * @Description:Object json格式输出
     * @param object
     * @param outputStream
     */
    @Override
    public void marshaller(Object object, OutputStream outputStream){
        try {
            JsonGenerator jsonGenerator = getObjectMapper().getJsonFactory().createJsonGenerator(outputStream,
                                              JsonEncoding.UTF8);

            getObjectMapper().writeValue(jsonGenerator, object);
        } catch (IOException e) {
            throw new OafException(e);
        }
    }

    /**
     * @Title:getObjectMapper
     * @Description:
     * @return
     * @throws IOException
     */
    private ObjectMapper getObjectMapper() throws IOException{
        if (this.objectMapper == null) {
            ObjectMapper           objectMapper        = new ObjectMapper();
            AnnotationIntrospector introspector        = new JaxbAnnotationIntrospector();
            SerializationConfig    serializationConfig = objectMapper.getSerializationConfig();

            serializationConfig = serializationConfig.without(SerializationConfig.Feature.WRAP_ROOT_VALUE).with(
                SerializationConfig.Feature.INDENT_OUTPUT).withAnnotationIntrospector(introspector);
            objectMapper.setSerializationConfig(serializationConfig);
            this.objectMapper = objectMapper;
        }

        return this.objectMapper;
    }
}
